package com.information.manage.basic.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class RedisUtils {

    @Autowired
    private RedisTemplate redisTemplate;


    public boolean setIfAbsent(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            result = operations.setIfAbsent(key, value, expireTime, timeUnit);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("设置失败，尚未连接到Redis服务器");
        }
        return result;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("设置失败，尚未连接到Redis服务器");
        }
        return result;
    }

    /**
     * 写入缓存设置时效时间
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("设置失败，尚未连接到Redis服务器");
        }
        return result;
    }

    /**
     * 批量删除对应的value
     *
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     *
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0) {
            redisTemplate.delete(keys);
        }
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    /**
     * 哈希 添加
     *
     * @param key
     * @param hashKey
     * @param value
     */
    public void hmSet(String key, Object hashKey, Object value) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.put(key, hashKey, value);
    }

    /**
     * hash移除
     * @param key
     * @param hashKey
     */
    public void hmDelete(String key, Object hashKey) {
        if (hmExist(key, hashKey)){
            HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
            hash.delete(key, hashKey);
        }
    }

    /**
     * 哈希 添加
     */
    public void hmSet(String key, Object hashKey, Object value, Long expireTime, TimeUnit timeUnit) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.put(key, hashKey, value);
        redisTemplate.expire(key, expireTime, timeUnit);
    }

    /**
     * 哈希 判断是否存在
     * @param key
     * @param hashKey
     * @return
     */
    public Boolean hmExist(String key, Object hashKey){
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        return hash.hasKey(key, hashKey);
    }

    /**
     * 哈希获取数据
     *
     * @param key
     * @param hashKey
     * @return
     */
    public Object hmGet(String key, Object hashKey) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        return hash.get(key, hashKey);
    }

    /**
     * 列表尾部添加
     * @param k
     * @param v
     */
    public void rPush(String k, Object v) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k, v);
    }

    /**
     * 列表右边添加
     * @param k  key
     * @param v  已经存在的某个值  如果该值不存在 不会添加
     * @param v1 添加的值
     */
    public void rPush(String k, Object v, Object v1) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k, v, v1);
    }

    /**
     * 列表添最前面加
     * @param k
     * @param v
     */
    public void lPush(String k, Object v) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.leftPush(k, v);
    }

    /**
     * 列表添加到某个元素的左边
     * @param k  key
     * @param v  已经存在的某个值  如果该值不存在 不会添加
     * @param v1 添加的值
     */
    public void lPush(String k, Object v, Object v1){
        ListOperations listOperations = redisTemplate.opsForList();
        Long aLong = listOperations.leftPush(k, v, v1);
    }

    /**
     * 列表获取
     * @param k
     * @param l  下标  从0开始的下标
     * @param l1   下标  从0开始的下标
     * 如果l=0 l1=-1 则获取全部
     * 如： k,3,5  会获取下标为3,4,5的元素 共3个     k,2,2 仅会获取下标为2的元素（即列表的第三个元素）
     * @return
     */
    public List<Object> lRange(String k, long l, long l1) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k, l, l1);
    }

    /**
     * 获取列表某个元素的下标
     * @param k
     * @param v
     * @return
     */
    public int getIndexFromList(String k, Object v){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k, 0, -1).indexOf(v);
    }

    /**
     * 更新
     * @param key
     * @param index 下标  从0开始的下标
     * @param value
     */
    public void setListValue(String key,int index, Object value){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.set(key, index, value);
    }

    /**
     * 删除
     * @param index 下标
     * @param value 对应的值
     */
    public void remListValue(String key, int index, Object value){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.remove(key, index, value);
    }

    /**
     * list移除元素
     * @param key
     * @param count  移除个数
     */
    public void lPop(String key,long count){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        for (int i = 0; i < count; i++) {
            list.leftPop(key);
        }
    }

    /**
     * 查看list的长度
     * @param key
     * return :long
     */
    public Long getListSize(String key){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.size(key);
    }

    /**
     * 集合添加
     *
     * @param key
     * @param value
     */
    public void add(String key, Object value) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key, value);
    }

    /**
     * 集合获取
     *
     * @param key
     * @return
     */
    public Set<Object> setMembers(String key) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     * 有序集合添加
     *
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key, Object value, double scoure) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key, value, scoure);
    }

    /**
     * 有序集合获取
     *
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }

    /**
     * 获取缓存的失效时间
     * @param key
     * @return
     */
    public long getExpire(final String key, TimeUnit timeUnit) {
        return redisTemplate.getExpire(key, timeUnit);
    }

    /**
     * 重置当前所有key
     */
    public void flushCurrentDatabase() {
        redisTemplate.execute((RedisCallback<Void>) connection -> {
            connection.flushDb();
            return null;
        });
    }

}